import { login, logout } from '@/api/home_'
import { getToken, setToken, removeToken } from '@/utils/auth'
const user = {
  state: {
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false
  },

  mutations: {
    SET_TOKEN: (state, token) => { // jk_ok
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles // 登录用户权限,[]会死循环
    },
    SET_LOAD_MENUS: (state, loadMenus) => { // ik_ok
      state.loadMenus = loadMenus
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const rememberMe = userInfo.rememberMe // 是否记住密码
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          // 登录成功后设置标识
          sessionStorage.removeItem('sysObj')
          setToken(res.access_token, rememberMe)
          sessionStorage.setItem('userInfo', JSON.stringify(res))//页面获取数据
          localStorage.setItem('userInfo', JSON.stringify(res))//url新打开获取不到用户信息
          commit('SET_TOKEN', res.access_token)
          setUserInfo(res, commit, []) // 配置权限
          commit('SET_LOAD_MENUS', true) // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        setUserInfo(user.state.user, commit, ['ADMIN']) // 配置权限
        resolve(user.state.user)
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          logOut(commit)
          resolve()
        }).catch(error => {
          logOut(commit)
          reject(error)
        })
      })
    },

    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_LOAD_MENUS', false)
      })
    }
  }
}

export const logOut = (commit) => {
  commit('SET_TOKEN', '')
  commit('SET_ROLES', [])
  removeToken()
  sessionStorage.clear()
}

export const setUserInfo = (res, commit, v) => {
  commit('SET_ROLES', v)// 设置权限，不调用会死循环
  commit('SET_USER', res)
}

export default user
